package cn.yj.netty.message.eventshander;

import cn.yj.netty.support.test.MessageProtocol;
import cn.yj.netty.common.CommandCode;
import cn.yj.netty.support.test.protocol.Header;
import io.netty.channel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * @author 永健
 * @since 2022-02-15 14:28
 */
public abstract class AbstractMessageHandler<T> implements MessageHandler<T> {
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    private ChannelHandlerContext context;

    @Override
    public void receiveMsg(T msg, ChannelHandlerContext channelHandlerContext) {
        this.context = channelHandlerContext;
        doHandler(msg);
    }

    protected void response(MessageProtocol messageProtocol) {
        Channel channel = context.channel();
        Header header = messageProtocol.getHeader();
        header.setTimestamp(new Date().getTime());
        if (channel.isOpen() && channel.isActive() && channel.isWritable()) {
            channel.writeAndFlush(messageProtocol);
            return;
        }
        log.warn("信道已关闭,open={},active={},isWritable={},channelId={},data={}", channel.isOpen(), channel.isActive(),
                channel.isWritable(), channel.id().asLongText(), messageProtocol.toProtocolStr());
    }

    protected boolean support(CommandCode commandCode, MessageProtocol msg) {
        return commandCode.getCode().equals(msg.getHeader().getCommandCode());
    }
    //    protected boolean support(Class aClass,MessageProtocol msg){
    //        Annotation[] annotations = aClass.getAnnotations();
    //        String value=this.getClass().getSimpleName();
    //        for (int i = 0; i < annotations.length; i++) {
    //            Annotation annotation = annotations[i];
    //            if (annotation.annotationType() == Component.class){
    //                value = ((Component) annotation).value();
    //                break;
    //            }
    //
    //            if (annotation.annotationType() == Service.class){
    //                value = ((Service) annotation).value();
    //                break;
    //            }
    //        }
    //        return value.equals(msg.getHeader().getCommandCode());
    //    }

    protected abstract void doHandler(T msg);
}
